package com.ctrip.cap;

import io.appium.java_client.AppiumDriver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctrip.cap.device.Device;
import com.ctrip.cap.device.DeviceStoreFactory;
import com.ctrip.cap.internal.domain.Context;
import com.ctrip.cap.lanucher.AppiumConfig;
import com.ctrip.cap.lanucher.AppiumServer;

/**
 * Appium Moblie
 *
 * @author ltyao
 */
public class AppiumContext extends Context {

    private static final Logger logger = LoggerFactory
            .getLogger(AppiumContext.class);

    private Device device;

    private AppiumDriver driver;

    private AppiumServer appium;

    private AppiumConfig appiumConfig;

    public Device getDevice() {
        return device;
    }

    public void setDevice(Device device) {
        this.device = device;
    }

    public AppiumDriver getDriver() {
        return driver;
    }

    public void setDriver(AppiumDriver driver) {
        this.driver = driver;
    }

    public AppiumServer getAppium() {
        return appium;
    }

    public void setAppium(AppiumServer appium) {
        this.appium = appium;
    }

    public AppiumConfig getAppiumConfig() {
        return appiumConfig;
    }

    public void setAppiumConfig(AppiumConfig appiumConfig) {
        this.appiumConfig = appiumConfig;
    }

    public void closeQuietly() {

        try {
            if (driver != null) {
                driver.quit();
                this.driver = null;
            }
        } catch (Exception e) {
            logger.warn("", e);
        }
        try {
            if (appium != null && appiumConfig.isCaseLevelRestart()) {
                appium.stopAppium();
                this.appium = null;
            }

        } catch (Exception e) {
            logger.warn("", e);
        }
        try {
            if (device != null) {
                DeviceStoreFactory.getDeviceStore().put(device);
                this.device = null;
            }
        } catch (Exception e) {
            logger.warn("", e);
        }
    }

}
